package com.codefactory.generator.service;

import com.codefactory.generator.model.ModelVO;
import com.codefactory.generator.model.TableColumn;
import com.codefactory.generator.model.TableVO;
import com.codefactory.generator.utils.CaseUtil;
import com.codefactory.generator.utils.DatabaseUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ModelService {
    @Autowired
    private DatabaseUtil databaseUtil;

    public List<ModelVO> generate(File tableNameFile) throws Exception {
        List<String> lines = FileUtils.readLines(tableNameFile, "UTF-8");
        return generate(lines);
    }

    public List<ModelVO> generate(String... tables) throws Exception {
        List<String> list = new LinkedList<>();
        for (String s : tables) list.add(s);
        return generate(list);
    }

    public List<ModelVO> generate(List<String> tableList) throws Exception {
        if (tableList == null || tableList.isEmpty()) return Collections.emptyList();
        Iterator<String> iterator = tableList.iterator();
        while (iterator.hasNext()) {
            if (StringUtils.isBlank(iterator.next())) iterator.remove();
        }
        if (tableList == null || tableList.isEmpty()) return Collections.emptyList();
        //
        Map<String, String> commentMap = databaseUtil.getTableCommentMap(tableList);
        Map<String, List<TableColumn>> listMap = databaseUtil.getColumnListForTables(tableList);
        List<ModelVO> voList = new ArrayList<>();

        for (String s : tableList) {
            TableVO vo = TableVO.create();
            ModelVO modelVO = ModelVO.create();
            vo.setTableName(s);
            vo.setTableComment(StringUtils.defaultString(commentMap.get(s)));
            vo.setClassName(CaseUtil.tableNameToClassName(s));
            vo.setVarName(CaseUtil.tableNameToVarName(s));
            List<TableColumn> columnList = listMap.get(s);
            List<String> columnNameList = columnList.stream().map(TableColumn::getColumnName).collect(Collectors.toList());
            modelVO.setTableInfo(vo);
            modelVO.setColumnList(columnList);
            modelVO.setColumnNameList(columnNameList);
            voList.add(modelVO);
        }
        return voList;
    }
}
